package gameengine.map;

import gameengine.map.unit.Unit;
import util.Logger;

public final class Attack extends java.lang.Thread implements Action {
    private static final long SLEEPTIME = 400;

    private final transient int xAttacked, yAttacked;
    private final transient int xAttacker, yAttacker;
    private transient Map map;
    private final transient int party;

    public Attack(final int xAttack, final int yAttack, final int xAttackedParam, final int yAttackedParam, final int partyParam) {
        super();
        this.xAttacker = xAttack;
        this.yAttacker = yAttack;
        this.xAttacked = xAttackedParam;
        this.yAttacked = yAttackedParam;
        this.party = partyParam;
    }

    @Override
    public void run() {
        final Unit attacker = this.map.getField(this.xAttacker, this.yAttacker).getUnit();
        final Unit attacked = this.map.getField(this.xAttacked, this.yAttacked).getUnit();
        if (attacker != null && attacked != null && attacker.canAttack()) {
            this.map.setReady(false);

            try {
                Thread.sleep(SLEEPTIME);
            } catch (final InterruptedException e) {
                Logger.d("Attack.run()", e.getMessage());
            }

            final int offense = attacker.getOffense();

            final int restPower = attacked.decreasePower(offense);
            if (restPower <= 0) {
                this.map.getField(this.xAttacked, this.yAttacked).setUnit(null);
                this.map.moveMent();
            }
        }

        this.map.setReady(true);
    }

    public String serialize() {
        return "ATTACK " + this.xAttacker + " " + this.yAttacker + " " + this.xAttacked + " " + this.yAttacked;
    }

    public boolean runAction(final Map mapParam) {
        this.map = mapParam;
        super.start();
        return true;
    }

    public int getParty() {
        return this.party;
    }
}
